#include "stdafx.h"
#include "Scene.h"

Scene::Scene(HWND hwnd, int width, int height) :
	m_hwnd(hwnd),
	m_viewport(0.0f, 0.0f, static_cast<float>(width), static_cast<float>(height)),
	m_scissorRect(0, 0, static_cast<LONG>(width), static_cast<LONG>(height))

{
	m_device = new Device(hwnd, width, height, 3, true);
	m_graphicsMemory = std::make_unique<GraphicsMemory>(m_device->GetDevice());
	m_device->CreateCommandList(m_commandAllocator, m_commandList);
	m_commandList->Close();
	m_states = std::make_unique<CommonStates>(m_device->GetDevice());

	m_batch = std::make_unique<PrimitiveBatch<VertexType>>(m_device->GetDevice());

	RenderTargetState rtState(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_D32_FLOAT);

	EffectPipelineStateDescription pd(
		&VertexType::InputLayout,
		CommonStates::Opaque,
		CommonStates::DepthDefault,
		CommonStates::CullNone,
		rtState);

	m_effect = std::make_unique<BasicEffect>(m_device->GetDevice(), EffectFlags::VertexColor, pd);

	Matrix proj = Matrix::CreateScale(2.f / float(width),
		-2.f / float(height), 1.f)
		* Matrix::CreateTranslation(-1.f, 1.f, 0.f);
	m_effect->SetProjection(proj);
}

void Scene::Render()
{
	m_commandAllocator->Reset();

	m_commandList->Reset(m_commandAllocator.Get(),nullptr);

	ID3D12DescriptorHeap* heaps[] = {  m_states->Heap() };
	m_commandList->SetDescriptorHeaps(_countof(heaps), heaps);

	m_commandList->RSSetViewports(1, &m_viewport);
	m_commandList->RSSetScissorRects(1, &m_scissorRect);
	ID3D12Resource* rt = m_device->GetRenderTargetResource();
	m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(rt, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));

	CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle = m_device->GetRenderTargetHandle();
	CD3DX12_CPU_DESCRIPTOR_HANDLE dsvHandle(m_device->GetDepthStencilHeap()->GetCPUDescriptorHandleForHeapStart());
	m_commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
	const float clearColor[] = { 0.5f, 0.2f, 0.4f, 0.5f };
	m_commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr);
	m_commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);

	m_effect->Apply(m_commandList.Get());

	m_batch->Begin(m_commandList.Get());

	VertexPositionColor v1(Vector3(400.f, 150.f, 0.f), Colors::Yellow);
	VertexPositionColor v2(Vector3(600.f, 450.f, 0.f), Colors::Yellow);
	VertexPositionColor v3(Vector3(200.f, 450.f, 0.f), Colors::Yellow);

	m_batch->DrawTriangle(v1, v2, v3);

	m_batch->End();

	m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT));
	m_commandList->Close();
	m_device->PostCommand(m_commandList.Get());
	m_device->Present();

}
